import express from "express";
import multer from "multer";
import path from "path";
import { networkInterfaces } from "systeminformation";
import { checkPortOccupied } from "../utils";

let server: any;
export async function startFileTransferService(
  url: string,
): Promise<{ status: number; data: string }> {
  if (server) {
    server.close();
    server = null;
  }
  const networkInterfacesData: any = await networkInterfaces();
  let ip4 = "";

  console.log(networkInterfacesData);

  for (const interfaceData of networkInterfacesData) {
    // 过滤出IPv4地址且不是内网接口（internal: false）
    if (interfaceData.ip4 && interfaceData.default) {
      ip4 = interfaceData.ip4;
      break;
    }
  }

  console.log(ip4);
  const port = 14965;
  const isPortOccupied = await checkPortOccupied(port);

  // 创建 express 应用
  const app = express();

  // 设置文件上传存储方式
  const storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, url); // 上传文件的存储路径
    },
    filename: function (req, file, cb) {
      cb(null, Date.now() + path.extname(file.originalname)); // 设置上传文件的名字
    },
  });

  // 初始化 multer 中间件
  const upload = multer({ storage: storage });

  // 创建上传接口
  app.post("/upload", upload.single("file"), (req, res) => {
    if (!req.file) {
      return res.status(400).send("No file uploaded.");
    }
    res.send({
      message: "File uploaded successfully",
      file: req.file,
    });
  });

  // 创建上传页面
  app.get("/", (req, res) => {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end(`
      <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" />
        <input type="submit" value="Upload" />
      </form>
    `);
  });

  // 启动服务器
  server = app.listen(port, () => {
    console.log(`Server started on http://${ip4}:${port}`);
  });

  return {
    status: 200,
    data: ip4 + ":" + port,
  };
}

export function stopFileTransferService() {
  if (server) {
    server.close();
    server.closeAllConnections(); // 强制关闭所有连接

    server = null;
    return {
      status: 200,
      data: "success",
    };
  }
}
